#include "uart_send_app.h"

osThreadId_t uart_send_TaskHandle;
const osThreadAttr_t uart_send_Task_attributes = {
  .name = "uart_Task",
  .stack_size = UART_TASK_STACK_SIZE * 4,
  .priority = (osPriority_t) UART_STORAGE_TASK_PRIORITY,
};

/* Calculate checksum */
uint8_t Calculate_Checksum(message_t *msg)
{
    uint8_t checksum = 0;
    uint8_t *data = (uint8_t*)msg;
    
    /* XOR all bytes except the checksum itself */
    for(size_t i = 0; i < (sizeof(message_t) - 1); i++)
    {
        checksum ^= data[i];
    }
    
    return checksum;
}

/* Fill message header */
void Fill_Message_Header(message_t *msg)
{
    /* Fill header */
    for(int i = 0; i < 4; i++)
    {
        msg->head = UART_SEND_HEAD_DATA;
    }
}

/* Send ADC data message */
int Send_ADC_Message(float *adc_data)
{
    message_t msg;
    
    /* Fill fixed header */
    Fill_Message_Header(&msg);
    
    /* Copy ADC data */
    memcpy(msg.adc_data, adc_data, sizeof(float) * 16);
    
    /* Calculate checksum */
    msg.check_bit = Calculate_Checksum(&msg);
    
    /* Send message via UART */
    if(HAL_UART_Transmit(&huart1, (const uint8_t*)&msg, sizeof(message_t), UART_SEND_TIME_OUT)) {
        return 0;    /* Transmission successful */
    }
    else {
        return -1;   /* Transmission failed */
    }
}

void uart_send_Task(void *argument)
{
  /* USER CODE BEGIN StartDefaultTask */
  /* Infinite loop */
    
    Queue_Init();
    
    float received_adc_data[16];
    
    for(;;)
    {
			xQueueReceive(xQueue_Uart, received_adc_data, portMAX_DELAY);
			
			#ifdef	UART_SEND
				if(0 == Send_ADC_Message(received_adc_data)) {
						/* Transmission successful */
				}
			#endif
			
			osDelay(10);
    }
  /* USER CODE END StartDefaultTask */
}
